package thread.safe;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.checkerframework.checker.units.qual.C;
import org.testng.annotations.Test;

public class TestReadWrite {

    @Test
    private void t1() {
        ArrayList<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);

        ExecutorService executorService = Executors.newFixedThreadPool(10);
        // 同时提交，和逐次提交
        for (int i = 0; i < 20; i++) {
            if (i % 2 == 0) {
                executorService.execute(new ReadThread(list));
            } else {
                executorService.execute(new WriteThread(list));
            }
        }
    }

    @Test
    private void t2() {
        ArrayList<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);

        // 不会有并发修改问题
        CopyOnWriteArrayList<Integer> copyList = new CopyOnWriteArrayList<>(list);

        ExecutorService executorService = Executors.newFixedThreadPool(10);
        // 同时提交，和逐次提交
        for (int i = 0; i < 20; i++) {
            if (i % 2 == 0) {
                executorService.execute(new ReadThread(copyList));
            } else {
                executorService.execute(new WriteThread(copyList));
            }
        }
    }
}
